package com.platform.sys.core.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import com.platform.core.consts.CommonConstant;
import com.platform.core.context.constant.ConstantContext;
import com.platform.core.enums.CommonStatusEnum;
import com.platform.core.exception.ServiceException;
import com.platform.sys.modular.consts.enums.SysConfigExceptionEnum;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 设置生成代码所需要数据的上下文
 *
 */
public class GenInitUtil {

    private static final Log log = Log.get();

    private static final String DATA_SOURCE_SQL = "select url,account,password from sys_data_source where status = ?";

    private static final String URL = "url";

    private static final String ACCOUNT = "account";

    private static final String PWASSWORD = "password";


    public static void onApplicationEvent(String url,String name,String password) {

        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 获取数据库连接配置
            String dataSourceUrlCurrent = url;
            String dataSourceUsernameCurrent = name;
            String dataSourcePasswordCurrent = password;

            conn = DriverManager.getConnection(dataSourceUrlCurrent, dataSourceUsernameCurrent, dataSourcePasswordCurrent);

            Entity dataSourceEntity = SqlExecutor.query(conn, DATA_SOURCE_SQL, new EntityHandler(), CommonStatusEnum.ENABLE.getCode());

            String dataSourceUrl = dataSourceEntity.getStr(URL);
            String dataSourceUsername = dataSourceEntity.getStr(ACCOUNT);
            String dataSourcePassword = dataSourceEntity.getStr(PWASSWORD);

            // 缓存中放入datasource链接，代码生成时候使用
            ConstantContext.putConstant(CommonConstant.DATABASE_URL_NAME, dataSourceUrl);
            ConstantContext.putConstant(CommonConstant.DATABASE_DRIVER_NAME, "com.mysql.cj.jdbc.Driver");
            ConstantContext.putConstant(CommonConstant.DATABASE_USER_NAME, dataSourceUsername);

            // 如果有为空的配置，终止执行
            if (ObjectUtil.hasEmpty(dataSourceUrl, dataSourceUsername)) {
                throw new ServiceException(SysConfigExceptionEnum.DATA_SOURCE_NOT_EXIST);
            }

        } catch (SQLException | ClassNotFoundException e) {
            log.error(">>> 读取数据库constants配置信息出错：");
            e.printStackTrace();
            throw new ServiceException(SysConfigExceptionEnum.DATA_SOURCE_NOT_EXIST);
        } finally {
            DbUtil.close(conn);
        }

    }
}
